//
//  DisherViewController.m
//  Recipe
//
//  Created by bing han on 12-7-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DisherViewController.h"
#import "DBOptions.h"
#import "FMDatabase.h"
#import "BaseUrl.h"
#import "TypeContentCell.h"
#import "TypeTitleCell.h"
#import "OrderList.h"
#import "DisherDetailViewController.h"
#import "OrderListViewController.h"
#import "SettingViewController.h"
#import "DisherType.h"
#import "DisherArray.h"
#import "DisherPosition.h"

#define UIVIEWWIDTH 220.0f
#define UIVIEWCONTENTWIDTH 200.0f
#define SPACEHEIGHT 30.0f
#define SPACEWIDTH  20.0f
#define INWIDTH 10.0f
#define INHEIGHT 10.0f


#define TAGADD 40000;
#define TAGSUBSTRACT 30000;
#define TAGUIVIEW 90000;
#define TAGCOUNT 20000;
#define TAGIMAGE 10000;
#define TAGIMAGEBUTTON 50000;

@interface DisherViewController ()

@end

@implementation DisherViewController
@synthesize typeArry = _typeArry,subtypeArry=_subtypeArry,disherArry=_disherArry;
@synthesize tabType=_tabType,scroll=_scroll;
@synthesize isOpenDict = _isOpenDict;
@synthesize typeDict = _typeDict;
@synthesize lblOrderCount = _lblOrderCount;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
//    _scroll.delegate = self;
    return self;
}

-(void) viewDidLoad{
    [super viewDidLoad];
    [self initType];
}

-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:YES];
    [self updateOrderCountLabel];
    
    [self initMenu];
    
    _scroll.layer.cornerRadius = 20;
    _scroll.layer.masksToBounds = YES;
    _scroll.userInteractionEnabled = YES;
    
    _tabType.backgroundView.alpha = 0;
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"dishershowbackground_02.png"]]];
}

-(void) initType{
    DisherType *dt = [DisherType newInstence];
    _typeArry = [[NSMutableArray alloc] initWithArray:dt.parentDisherType];
    
    if ([_typeArry count] >0) {
        [self initTypeDict];
    }else{
        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        [result setValue:@"尚未更新菜品" forKey:@"typecn"];
        [_typeArry addObject:result];
    }
    [_tabType reloadData];
}

-(void) initMenu{
    DisherArray *da = [DisherArray newInstence];
    _disherArry = [[NSMutableArray alloc] initWithArray:da.disherArray];
    [self updateScrollView:_disherArry];
    [self updateScrollFallsView];
}

-(void) initTypeDict{
    DisherType *dt = [DisherType newInstence];
    _typeDict = [[NSMutableDictionary alloc] initWithDictionary:dt.allDisherType];
    _isOpenDict = [[NSMutableDictionary alloc] init];
    
    NSDictionary *type = nil;    
    for (int i = 0; i< [_typeArry count]; i++) {
        type = [_typeArry objectAtIndex:i];
        NSString *key = [type objectForKey:@"key"];        
        [_isOpenDict setObject:@"0" forKey:key];
        [key release];
    }
}

#pragma mark --
#pragma button click

//显示设置
-(IBAction)showSet:(id)sender{
    SettingViewController *setViewCtl= [[SettingViewController alloc] init];
    setViewCtl.delegate = self;
    setViewCtl.modalInPopover = NO;
    setViewCtl.modalPresentationStyle = UIModalPresentationFormSheet;
    setViewCtl.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:setViewCtl animated:YES];
    [setViewCtl release];
}

-(void) dissmissview{
    [[self modalViewController] dismissModalViewControllerAnimated:YES];
}

//显示已点菜单表
-(IBAction)showOrderList:(id)sender{
    OrderList *ol = [OrderList newInstance];
    
    if ([ol.disherOrder count] <= 0) {
        UIAlertView *showMsg = [[UIAlertView alloc] initWithTitle:@"提示"  message:@"您还没有点菜" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [showMsg show];
    }else {
//        [self retainImageView];
        OrderListViewController *olv = [[OrderListViewController alloc] initWithNibName:@"OrderListViewController" bundle:nil];
        [self.navigationController pushViewController:olv animated:YES];
        
        [olv release];
    }
}

-(void) clearScrollView{
    for (UIView *ui in _scroll.subviews) {
        [ui removeFromSuperview];
    }
}
-(void) updateScrollView:(NSArray *) dishers{
    [self clearScrollView];
    
    DisherPosition *dp = [DisherPosition newInstence];
    NSString *oldType = @"";
    
    //每行中，每列所在的x坐标值，固定值
    NSArray *rowX = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:SPACEWIDTH]
                     ,[NSNumber numberWithFloat:(SPACEWIDTH * 2 + UIVIEWWIDTH)]
                     ,[NSNumber numberWithFloat:(SPACEWIDTH * 3 + UIVIEWWIDTH * 2)]
                     , nil];
    
    //每列中，每一个uiview所在的y坐标值，需要在每一个uiview画完后计算
    NSMutableArray *rowY = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:SPACEHEIGHT],
                            [NSNumber numberWithFloat:SPACEHEIGHT],
                            [NSNumber numberWithFloat:SPACEHEIGHT], nil];
    //scrollview content height 计算值
    CGFloat scrollContentHeight = 0.0f;
    //计算每个uiview 的height
    //    CGFloat contentHeight = 0.0f;
    int rownum = 1;
    
    for (int i =0 ; i < [dishers count]; i++) {
        int modelval = i % 3;
        if (modelval == 2) {
            rownum += 1;
        }
        
        NSDictionary *disher = [dishers objectAtIndex:i];
        NSString *type = [disher objectForKey:@"type"];
        NSString *price = [disher objectForKey:@"cprice"];
        NSString *cnname = [disher objectForKey:@"cnamecn"];
        NSString *imagepath = [disher objectForKey:@"smallimage"];
        UIImage *smallimage = [UIImage imageWithContentsOfFile:imagepath];
        
        CGFloat contentY = 0.0f;
        
        CGFloat imageViewHeigh = UIVIEWCONTENTWIDTH * smallimage.size.height / smallimage.size.width;
        CGRect imageRect = CGRectMake(INWIDTH, INHEIGHT, UIVIEWCONTENTWIDTH, imageViewHeigh);
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageRect];
        //        ScrollImageView *imageView = [[ScrollImageView alloc] initWithFrame:imageRect];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.tag = i + TAGIMAGE;
        
        //覆盖在图片上的button
        UIButton *imgBtn = [[UIButton alloc] initWithFrame:imageRect];
        imgBtn.backgroundColor = [UIColor clearColor];
        [imgBtn addTarget:self action:@selector(imgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        imgBtn.tag =  i + TAGIMAGEBUTTON;
        
        contentY += imageViewHeigh + 5.0f;
        
        //菜名
        CGRect cnameRect = CGRectMake(INWIDTH, contentY, UIVIEWCONTENTWIDTH * 3 / 5, 40);
        UILabel *lbname = [[UILabel alloc] initWithFrame:cnameRect];
        lbname.text = cnname;
        lbname.font = [UIFont fontWithName:@"System Bold" size:20];
        //菜名，价格在一行
        //        contentY += cnameRect.size.height + 5.0f;
        //价格
        CGRect priceRect = CGRectMake(INWIDTH + UIVIEWCONTENTWIDTH * 3 / 5, contentY , UIVIEWCONTENTWIDTH * 2 / 5 , 40);
        UILabel *lbprice = [[UILabel alloc] initWithFrame:priceRect];
        lbprice.text = [NSString stringWithFormat:@"%@ 元",price];;
        lbprice.textColor = [UIColor redColor];
        
        lbprice.font = [UIFont fontWithName:@"System Bold" size:20];
        //数量显示
        CGRect countLabRrect = CGRectMake(INWIDTH + UIVIEWCONTENTWIDTH  - 68 , contentY - 32, 30.0f, 30.0f);
        UILabel *countLab = [[UILabel alloc] initWithFrame:countLabRrect];
        countLab.backgroundColor = [UIColor lightTextColor];
        countLab.textAlignment = UITextAlignmentCenter;
        countLab.layer.cornerRadius = 5;
        countLab.layer.masksToBounds = YES;
        OrderList *ol = [OrderList newInstance];
        NSString *tmpcount = [ol.disherOrder objectForKey:[disher objectForKey:@"businesskey"]];
        int tmpcountval = [tmpcount intValue];
        if (tmpcountval > 0) {
            countLab.text = tmpcount;
            [countLab setHidden:NO];
        }else {
            [countLab setHidden:YES];
        }
        
        countLab.tag = i + TAGCOUNT;
        countLab.textColor = [UIColor redColor];
        
        //减少按钮
        CGRect subtractDisherRect = CGRectMake(INWIDTH + UIVIEWCONTENTWIDTH  - 100 , contentY - 35, 37.0f, 37.0f);
        UIButton *subtractButton = [UIButton buttonWithType:UIButtonTypeCustom];
        subtractButton.frame = subtractDisherRect;
        NSString *removeBtnPath = [[NSBundle mainBundle] pathForResource:@"removebutton"
                                                         ofType:@"png"];

        [subtractButton setImage:[UIImage imageWithContentsOfFile:removeBtnPath] forState:UIControlStateNormal];
        subtractButton.tag = i + TAGSUBSTRACT;
        [subtractButton addTarget:self action:@selector(subtractBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        if (tmpcountval > 0) {
            countLab.text = tmpcount;
            [subtractButton setHidden:NO];
        }else {
            [subtractButton setHidden:YES];
        }
        
        //增加按钮
        CGRect orderDisherRect = CGRectMake(INWIDTH + UIVIEWCONTENTWIDTH  - 40 , contentY - 35, 37.0f, 37.0f);
        UIButton *orderButton = [UIButton buttonWithType:UIButtonTypeCustom];
        orderButton.frame = orderDisherRect;
        NSString *addBtnPath = [[NSBundle mainBundle] pathForResource:@"addbutton"
                                                                  ofType:@"png"];
        [orderButton setImage:[UIImage imageWithContentsOfFile:addBtnPath] forState:UIControlStateNormal];
        
        orderButton.tag = i + TAGADD;
        [orderButton addTarget:self action:@selector(orderBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //本个uiview的内容高度
        CGFloat contentHeight = contentY + priceRect.size.height;
        //本格uiview所在的x、y值
        CGFloat uiviewX = [[rowX objectAtIndex:modelval] floatValue];
        CGFloat uiviewY = [[rowY objectAtIndex:modelval] floatValue];
        //下一个uiview 所在的y值 SPACEHEIGHT * rownum + 
        CGFloat uiviewNextY = uiviewY + SPACEHEIGHT + contentHeight;
        
        NSNumber *ny = [NSNumber numberWithFloat:uiviewNextY];
        [rowY replaceObjectAtIndex:modelval withObject:ny];
        
        CGRect uvRect = CGRectMake(uiviewX, uiviewY, UIVIEWWIDTH, contentHeight);
        
//        if (uiviewY > _scroll.frame.size.height) {
            imageView.image = nil;
//        } else {
//            imageView.image = smallimage;
//        }
        
        UIView *uview = [[UIView alloc] initWithFrame:uvRect];
        uview.tag = i + TAGUIVIEW;
        uview.backgroundColor = [UIColor whiteColor];
        [uview addSubview:imgBtn];
        [uview addSubview:imageView];
        [uview addSubview:lbname];
        [uview addSubview:lbprice];
        [uview addSubview:orderButton];
        [uview addSubview:subtractButton];
        [uview addSubview:countLab];
        
        if (![type isEqualToString:oldType]) {
            oldType = type;
            [dp addPosition:type position:[NSString stringWithFormat:@"%f",uiviewY]];
        }
        [imageView release];
        [lbname release];
        [lbprice release];
        //        [orderButton release];
        [_scroll addSubview:uview];
//        [_disherUIViewArray addObject:uview];
        [uview release];
    }
    for (int i = 0; i < [rowY count]; i++) {
        NSNumber *rowheight = [rowY objectAtIndex:i];
        scrollContentHeight = scrollContentHeight > [rowheight floatValue] ? scrollContentHeight :[rowheight floatValue];
    }
    _scroll.contentSize = CGSizeMake(_scroll.frame.size.width, scrollContentHeight);
}

-(void) updateScrollFallsView{
    CGPoint offset = _scroll.contentOffset;
    CGFloat cacheHeight = _scroll.frame.size.height * 1;   //缓存页面高度
    for (UIView *ui in _scroll.subviews) {
        if ((ui.frame.origin.y + ui.frame.size.height) <= offset.y - cacheHeight) {
            //uiview 在当前可视区域上边
            for (UIImageView *uiiv in ui.subviews) {
                if ([uiiv isKindOfClass:[UIImageView class]]) {
//                    uiiv.image = nil;
                    break;
                }
            }
        } else if (ui.frame.origin.y > (offset.y + _scroll.frame.size.height) + cacheHeight ) {
            //uiview 在当前可视区域下方
            for (UIImageView *uiiv in ui.subviews) {
                if ([uiiv isKindOfClass:[UIImageView class]]) {
//                    uiiv.image = nil;
                    break;
                }
            }
        } else {
            for (UIImageView *uiiv in ui.subviews) {
                if ([uiiv isKindOfClass:[UIImageView class]]) {
                    
                    int tag = uiiv.tag;
                    tag -= TAGIMAGE;
                    NSDictionary *tmpdict = [[NSDictionary alloc] initWithDictionary:[_disherArry objectAtIndex:tag]];
                    UIImage *image = [UIImage imageWithContentsOfFile:[tmpdict objectForKey:@"smallimage"]];
                  if (!uiiv.image) {
                    uiiv.image = image;
                  }
                    
                    break;
                }
            }
        }
    }
}

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{
    [self updateScrollFallsView];
}

-(IBAction)orderBtnClick:(id)sender{
    UIButton *btn = (UIButton*) sender;
    int tmptag = btn.tag - TAGADD;
    for (UIView *uvw in _scroll.subviews) {
        int uvwtag = tmptag + TAGUIVIEW;
        if (uvw.tag == uvwtag) {
            for (UILabel *tmplb in uvw.subviews) {
                int labtag = tmptag + TAGCOUNT
                if (tmplb.tag == labtag) {
                    [tmplb setHidden:NO];
                    [self checkSubstractBtn:tmptag showOrHidder:NO];
                    [self updateOrderList:tmptag value:1];
                    OrderList *ol = [OrderList newInstance];
                    NSDictionary *tmpdic = [_disherArry objectAtIndex:tmptag];
                    
                    NSString *tmplbl = [ol.disherOrder objectForKey:[tmpdic objectForKey:@"businesskey"]];
                    tmplb.text = tmplbl;
                }
            }
            break;
        }
        
    }
    
}

-(IBAction)subtractBtnClick:(id)sender{
    UIButton *btn = (UIButton*) sender;
    int tmptag = btn.tag - TAGSUBSTRACT;
    for (UIView *uvw in _scroll.subviews) {
        int uvwtag = tmptag + TAGUIVIEW;
        if (uvw.tag == uvwtag) {
            for (UILabel *tmplb in uvw.subviews) {
                int labtag = tmptag + TAGCOUNT
                if (tmplb.tag == labtag) {
                    int countval = [tmplb.text intValue];
                    countval -=1;
                    [self updateOrderList:tmptag value:-1];
                    if (countval == 0) {
                        [tmplb setHidden:YES];
                        [self checkSubstractBtn:tmptag showOrHidder:YES];
                    }
                    OrderList *ol = [OrderList newInstance];
                    NSDictionary *tmpdic = [_disherArry objectAtIndex:tmptag];
                    
                    NSString *tmplbl = [ol.disherOrder objectForKey:[tmpdic objectForKey:@"businesskey"]];
                    tmplb.text = tmplbl;
                }
            }
            break;
        }
        
    }
}

-(void) checkSubstractBtn:(NSInteger) tag showOrHidder:(BOOL) show{
    for (UIView *uvw in _scroll.subviews) {
        int uvwtag = tag + TAGUIVIEW;
        if (uvw.tag == uvwtag) {
            for (UIButton *tmplb in uvw.subviews) {
                int labtag = tag + TAGSUBSTRACT
                if (tmplb.tag == labtag) {
                    [tmplb setHidden:show];                
                }
            }
        }
    }
}

//更新系统点菜列表
-(void) updateOrderList:(int)tag value:(NSInteger) value{
    NSDictionary *disher = [_disherArry objectAtIndex:tag];
    OrderList *ol = [OrderList newInstance];
    if (value > 0) {
        [ol addDisher:[disher objectForKey:@"businesskey"]];
    }else{
        [ol substractDisher:[disher objectForKey:@"businesskey"]];
    } 
    [self updateOrderCountLabel];
}

-(void) updateOrderCountLabel{
    OrderList *ol = [OrderList newInstance];
    int tmpcount = [ol.disherOrder count];
    if (tmpcount > 0) {
        [_lblOrderCount setHidden:NO];
        _lblOrderCount.text = [NSString stringWithFormat:@"%i",tmpcount];
    }else {
        [_lblOrderCount setHidden:YES];
    }
}

-(IBAction)imgBtnClick:(id)sender{
//    [self retainImageView];
    UIButton *btn = (UIButton*) sender;
    int tmptag = btn.tag - TAGIMAGEBUTTON;
    NSDictionary *disher = [_disherArry objectAtIndex:tmptag];
    DisherDetailViewController *disherDetail = [[DisherDetailViewController alloc] initWithNibName:@"DisherDetailViewController" bundle:nil];
    [self.navigationController pushViewController:disherDetail animated:YES];
    
    [disherDetail initWithDict:disher count:[self getDisherOrderCount:tmptag]];
    
    [disherDetail release];
}

-(NSInteger) getDisherOrderCount:(NSInteger) tmptag{
    for (UIView *uvw in _scroll.subviews) {
        int uvwtag = tmptag + TAGUIVIEW;
        if (uvw.tag == uvwtag) {
            for (UILabel *tmplb in uvw.subviews) {
                int labtag = tmptag + TAGCOUNT
                if (tmplb.tag == labtag) {
                    int countval = [tmplb.text intValue];
                    return countval;
                }
            }
        }
    }
    return 0;
}

#pragma --
#pragma mark -- tableview delegate
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return [_typeArry count];
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *selectDict = [_typeArry objectAtIndex:section];
    NSString *selectKey = [selectDict objectForKey:@"key"];
    
    NSArray *array = [_typeDict objectForKey:selectKey];
    NSString *open = [_isOpenDict objectForKey:selectKey];
    BOOL isOpen = [open isEqualToString:@"1"];
    if (isOpen) {
        return [array count] + 1;
    }else {
        return 1;
    }
    
}

-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    NSInteger section = [indexPath section];
    
    NSDictionary *selectDict = [_typeArry objectAtIndex:section];
    NSString *selectKey = [selectDict objectForKey:@"key"];
    NSString *selectTitle = [selectDict objectForKey:@"typecn"];
    NSArray *source = [_typeDict objectForKey:selectKey];
    
    UITableViewCell* cell = nil;
    if (row == 0) {
        cell = [self titleCell:selectTitle source:source];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }else {
        cell = [self contentCellForRow:row - 1 source:source];
    }
    return  cell;
} 

- (UITableViewCell *) titleCell:(NSString *)key source:(NSArray *) source{
    
	NSString* titleCellIdentifier = [NSStringFromClass([self class]) stringByAppendingString:@"title"];
	
	TypeTitleCell *cell = [_tabType dequeueReusableCellWithIdentifier:titleCellIdentifier];
	if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TypeTitleCell" owner:self options:nil] lastObject];
	}
	cell.cellContent.text = key;
	if ([source count] != 0) {
		cell.detailTextLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%i 个分类",), [source count]];
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        //        [self setAccessoryViewOnCell:cell];
	}
	else {
		cell.detailTextLabel.text = NSLocalizedString(@"没有分类",);
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryView = nil;
        cell.textLabel.textColor = [UIColor blackColor];
	}
	
	return cell;
}

- (UITableViewCell *) contentCellForRow:(NSUInteger)row source:(NSArray *) source{
	NSString* contentCellIdentifier = [NSStringFromClass([self class]) stringByAppendingString:@"content"];
	
    TypeContentCell *cell = [_tabType dequeueReusableCellWithIdentifier:contentCellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TypeContentCell" owner:self options:nil] lastObject];
    }
    NSDictionary *cellDic = [source objectAtIndex:row];
    cell.cellContent.text = [cellDic objectForKey:@"typecn"];
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger sectionid = indexPath.section;    
    NSDictionary *selectDict = [_typeArry objectAtIndex:sectionid];
    NSString *selectKey = [selectDict objectForKey:@"key"];
    
    NSArray *source = [_typeDict objectForKey:selectKey];
    NSString *open = [_isOpenDict objectForKey:selectKey];
    BOOL isOpen = [open isEqualToString:@"1"];
    if (row == 0){
        if (isOpen) {
            [_isOpenDict setObject:@"0" forKey:selectKey];
        }else {
            [_isOpenDict setObject:@"1" forKey:selectKey];
        }
        [self didSelectTitleCell:source open:isOpen];
        
    } else {
        [self didSelectContentCellAtRow:indexPath];
    }
}

- (void) didSelectTitleCell:(NSArray *) source open:(BOOL) Open {
	Open = !Open;
    
	NSIndexPath* indexPath = [_tabType indexPathForSelectedRow];
	NSUInteger section = indexPath.section;
	NSUInteger contentCount = [source count];
	
	[_tabType beginUpdates];
	
	NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
	for (NSUInteger i = 1; i < contentCount + 1; i++) {
		NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
		[rowToInsert addObject:indexPathToInsert];
	}
	
	if (Open) 
        [_tabType insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
	else 
        [_tabType deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
	[rowToInsert release];
	
	[_tabType endUpdates];
	
	if (Open) 
        [_tabType scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
	[_tabType deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) didSelectContentCellAtRow:(NSIndexPath*)indexPath {
    NSInteger selectRow = indexPath.row;
    if (selectRow >0) {
        int selectSection = indexPath.section;
        
        NSDictionary *selectDict = [_typeArry objectAtIndex:selectSection];
        NSString *selectKey = [selectDict objectForKey:@"key"];
        NSArray *selectArray = [_typeDict objectForKey:selectKey];
        NSMutableDictionary *selectType = [selectArray objectAtIndex:selectRow-1];
        NSString *typeKey = [selectType objectForKey:@"key"];
//        [self updateDishers:typeKey];
        
        DisherPosition *dl = [DisherPosition newInstence];
        NSString *position = [dl.disherPostion objectForKey:typeKey];
        CGFloat posit = [position floatValue];
        
        CGPoint defaultPoint = _scroll.contentOffset;
        defaultPoint.y = posit;
        
        if (defaultPoint.y >= _scroll.contentSize.height) {
            defaultPoint.y = _scroll.contentSize.height;
        }
        
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        _scroll.contentOffset = defaultPoint;
        [UIView commitAnimations];
        
      /**
        NSLog(@"typecn:%@ ,posti:%f , contentoffset.y:%f",@"",posit,_scroll.contentOffset.y);
        
        CGPoint move = _scroll.contentOffset;
        CGFloat my = move.y;
        if (posit > _scroll.contentOffset.y) {
            
            do {
                my += _scroll.frame.size.height;
                move.y = my;
                if (move.y > defaultPoint.y) {
                    move.y = defaultPoint.y;
                }
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:2.0f];
//                [UIView setAnimationBeginsFromCurrentState:YES];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                _scroll.contentOffset = move;
                [UIView commitAnimations];
            } while (my <= defaultPoint.y);
        } else {
            do {
                my -= _scroll.frame.size.height;
                move.y = my;
                if (move.y < defaultPoint.y) {
                    move.y = defaultPoint.y;
                }
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:2.0f];
//                [UIView setAnimationBeginsFromCurrentState:YES];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                _scroll.contentOffset = move;
                [UIView commitAnimations];
            } while (my >= defaultPoint.y);
        }
       **/
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.row >0) {
        return 50;
    }
    return 60;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
//    _typeArry  = nil;
//    _subtypeArry  = nil;
//    _disherArry  = nil;
    _tabType  = nil;
    _scroll  = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

@end

//-(void) updateScrollFallsView:(NSMutableArray *)disherArray{
//    float offSetY = _scroll.contentOffset.y;
//    float contentHeight = _scroll.frame.size.height;
//    float halfPage = _scroll.frame.size.height / 2;
//    
//    
//    for (UIView *disherView in _scroll.subviews) {
//        if (disherView.frame.origin.y < (offSetY - halfPage) && (disherView.frame.origin.y + disherView.frame.size.height) > (offSetY - halfPage)) {
//            //下半部露出的情况
//            for (UIImageView *uiiv in disherView.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {                    
//                    int tag = uiiv.tag;
//                    tag -= TAGIMAGE;
//                    NSDictionary *tmpdict = [[NSDictionary alloc] initWithDictionary:[_disherArry objectAtIndex:tag]];
//                    UIImage *image = [UIImage imageWithContentsOfFile:[tmpdict objectForKey:@"smallimage"]];
//                    uiiv.image = image;
//                    break;
//                }
//            }
//            [_scroll addSubview:disherView];
//        }else if(disherView.frame.origin.y > (offSetY - halfPage) && disherView.frame.origin.y + disherView.frame.size.height <  offSetY + contentHeight + halfPage){
//            //整体露出的情况
//            for (UIImageView *uiiv in disherView.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {                    
//                    int tag = uiiv.tag;
//                    tag -= TAGIMAGE;
//                    NSDictionary *tmpdict = [[NSDictionary alloc] initWithDictionary:[_disherArry objectAtIndex:tag]];
//                    UIImage *image = [UIImage imageWithContentsOfFile:[tmpdict objectForKey:@"smallimage"]];
//                    uiiv.image = image;
//                    break;
//                }
//            }
//        }else if(disherView.frame.origin.y < (offSetY + contentHeight + halfPage) && (disherView.frame.origin.y + disherView.frame.size.height )> offSetY + contentHeight + halfPage) {
//            //上半部露出的情况
//            for (UIImageView *uiiv in disherView.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {                    
//                    int tag = uiiv.tag;
//                    tag -= TAGIMAGE;
//                    NSDictionary *tmpdict = [[NSDictionary alloc] initWithDictionary:[_disherArry objectAtIndex:tag]];
//                    UIImage *image = [UIImage imageWithContentsOfFile:[tmpdict objectForKey:@"smallimage"]];
//                    uiiv.image = image;
//                    break;
//                }
//            }
//        }else {
//        }
//    }
//    //    NSLog(@"i= %d",i);
//}


//-(void) updateDishers:(NSString*) type{
//    if (type==nil || [type isEqualToString:@""]) {
//        return;
//    }
//    
//    DBOptions *dbOption = [DBOptions newInstence];
//    FMDatabase *fmdb = dbOption.fmdatabase;
//    _disherArry = [[NSMutableArray alloc] init];
//    
//    FMResultSet *rsdisher = [fmdb executeQuery:@"select * from dishes where type=?",type];
//    while ([rsdisher next]) {
//        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
//        [result setValue:[rsdisher objectForColumnName:@"businesskey"] forKey:@"businesskey"];
//        [result setValue:[rsdisher objectForColumnName:@"type"] forKey:@"type"];
//        [result setValue:[rsdisher objectForColumnName:@"cnamecn"] forKey:@"cnamecn"];
//        [result setValue:[rsdisher objectForColumnName:@"cnameen"] forKey:@"cnameen"];
//        [result setValue:[rsdisher objectForColumnName:@"remarks"] forKey:@"remarks"];
//        NSString *smallfile = [[rsdisher objectForColumnName:@"businesskey"] stringByAppendingString:@"small"];
//        smallfile = [DISHERIMAGEPATH stringByAppendingString:smallfile];
//        UIImage *smallimage = [UIImage imageWithContentsOfFile:smallfile];
//        [result setValue:smallimage forKey:@"smallimage"];
//        
//        NSString *bigfile = [[rsdisher objectForColumnName:@"businesskey"] stringByAppendingString:@"big"];
//        bigfile = [DISHERIMAGEPATH stringByAppendingString:bigfile];
//        UIImage *bigimage = [UIImage imageWithContentsOfFile:bigfile];
//        [result setValue:bigimage forKey:@"bigimage"];
//        
//        [result setValue:[rsdisher objectForColumnName:@"cprice"] forKey:@"cprice"];
//        [_disherArry addObject:result];
//        [result release];
//    }
//    [dbOption closeDatabase];
//    
//    [self updateScrollView:_disherArry];
//}

//-(IBAction)changeImage:(id)sender{
//
//    CGPoint offset = _scroll.contentOffset;
//    NSLog(@"offset.y = %f",offset.y);
//
//    for (UIView *ui in _scroll.subviews) {
//        
//        if ((ui.frame.origin.y + ui.frame.size.height) <= offset.y) {
//            //uiview 在当前可视区域上边
//            for (UIImageView *uiiv in ui.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {
//                    uiiv.image = nil;
//                    break;
//                }
//            }
//        } else if (ui.frame.origin.y > (offset.y + _scroll.frame.size.height)) {
//            //uiview 在当前可视区域下方
//            for (UIImageView *uiiv in ui.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {
//                    uiiv.image = nil;
//                    break;
//                }
//            }
//        } else {
//            for (UIImageView *uiiv in ui.subviews) {
//                if ([uiiv isKindOfClass:[UIImageView class]]) {
//                    int tag = uiiv.tag;
//                    tag -= TAGIMAGE;
//                    NSDictionary *tmpdict = [[NSDictionary alloc] initWithDictionary:[_disherArry objectAtIndex:tag]];
//                    UIImage *image = [UIImage imageWithContentsOfFile:[tmpdict objectForKey:@"smallimage"]];
//                    uiiv.image = image;
//                    
////                    UIImageView *tmpimgv = [[UIImageView alloc] initWithFrame:uiiv.frame];
////                    tmpimgv.image = image;
////                    tmpimgv.tag = uiiv.tag;
////                    [uiiv removeFromSuperview];
////                    [ui addSubview:tmpimgv];
////                    [tmpimgv release];
//                    [image release];
//
//                    break;
//                }
//            }
//        }
//    }
//
//}

//-(void) retainImageView{
//    for (UIView *viw in _scroll.subviews) {
//        //        [viw retain];
//        for (UIImageView *uiiv in viw.subviews) {
//            [uiiv retain];
//        }
//    }
//}
